package com.zhuqiandann.scis.controller;

import com.zhuqiandann.scis.common.JsonResult;
import com.zhuqiandann.scis.common.PageJson;
import com.zhuqiandann.scis.model.Paper;
import com.zhuqiandann.scis.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/paper")
public class AdminPaperController extends BaseController{
    @Autowired
    PaperService paperService;



    @GetMapping("/list")
    @ResponseBody
    public PageJson<Paper> all(ModelMap map){
        List<Paper> paperList = paperService.findAll();
        PageJson<Paper> page = new PageJson<>();
        page.setCode(0);
        page.setMsg("成功");
        page.setCount(paperList.size());
        page.setData(paperList);
        return page;
    }

    @GetMapping("/form")
    public String form(@RequestParam(required = false) Integer id, ModelMap map){

        if(id != null){
            Paper paper = paperService.findById(id);
            map.put("paper",paper);
        }
        return "admin/paper/form";
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(Paper paper){
        try {
            paperService.saveOrUpdate(paper);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok();
    }

    @DeleteMapping("{id}/del")
    @ResponseBody
    public JsonResult del(@PathVariable("id") Integer id){
        try {
            paperService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail("删除失败");
        }
        return JsonResult.ok();
    }


}
